// STATIC VERSION

google.load("maps", "3", { "other_params": "sensor=true" });
google.load("earth", "1");

function loadDemo(sector) {
    // the parameter sector will be either "telco", "utilities", "resource", "government" or "financial"
    // please instantiate the demo into #demoholder and call startDemo when earth is loaded.

    // sample earth plugin
    google.earth.createInstance('demoholder', initCB, failureCB);

}
function startDemo() {
    $(".earthshim, #earth").remove();
}

function initCB(instance) {
    ge = instance;
    ge.getWindow().setVisibility(true);
    startDemo();
}
function failureCB(errorCode) {
}
var ge;
var map;
var tiles = [];
var motionInterval = 0;
function init() {
    var start = new google.maps.LatLng(0, 0);
    var located = false;
    if (google.loader.ClientLocation) {
        located = true;
        start = new google.maps.LatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude);
    }
    var myOptions = {
        zoom: 5,
        center: start,
        disableDefaultUI: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        scrollwheel: false,
        disableDoubleClickZoom: true
    };
    map = new google.maps.Map(document.getElementById('map'), myOptions);
    map.setMapTypeId(google.maps.MapTypeId.SATELLITE);

    var visibleTiles = new Array();
    var invisibleTiles = new Array();
    // var invisible = [4, 11, 17, 21, 22];

    google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
        $(".main-info div.default, .verticals, .grid").delay(1000).fadeIn(1000);
        var ieOld = $(".lt-ie9").length > 0;
        if (!ieOld) {
            // randomize invisible rectangles
            
            for (var i = 0; i < tiles.length; i++) {
                if ($(tiles)[i].type == "rect")
                    visibleTiles.push(i);
                else 
                    invisibleTiles.push(i);
            }
            visibleTiles.sort(function() { return 0.5 - Math.random();});
            
            //for (var i=0; i < visibleTiles.length; i++) {
                //if ($.inArray(visibleTiles[i], invisible) == -1)
            for (var i=0; i < visibleTiles.length - 5; i++) {
                    $(tiles[visibleTiles[i]].el.node).delay(1000).delay(Math.floor(Math.random() * 1250)).animate({ 'opacity': 0.55 }, 500);    
            }
        }
        setTimeout(function () { $(".main-info div").vAlign(); }, 1100);

    });
    if (!located) {
        if (navigator.geolocation) {
            browserSupportFlag = true;
            navigator.geolocation.getCurrentPosition(function (position) {
                start = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.panTo(start);
            }, function (error) {
                // no need to do anything
            });
            // Try Google Gears Geolocation
        } else if (google.gears) {
            browserSupportFlag = true;
            var geo = google.gears.factory.create('beta.geolocation');
            geo.getCurrentPosition(function (position) {
                start = new google.maps.LatLng(position.latitude, position.longitude);
                map.panTo(start);
            }, function (error) {
                // no need to do anything
            });
        }
    }
    var x = 0;
    var dir = 1;
    motionInterval = setInterval(function () {
        // randomly fade out a tile and fade in another invisible tile at random intervals
        randomSwapTile();
    }, (1000 + Math.floor(Math.random() * 3100)));
}

function randomSwapTile() {
    // randomly fade toggle 1 of each type
    var imageTilesCount = $("#tiles image").length/2;
    var totalRectCount = $("#tiles rect").length;
    var fadeableRectCount = totalRectCount - imageTilesCount - 1;  // the extra 1 is the info panel
    var fadeableTiles = $("#tiles rect:lt(" + fadeableRectCount + ")");
        
    var vis = fadeableTiles.filter(function() { return $(this).css('opacity') > 0; });
    var invis = fadeableTiles.filter(function() { return $(this).css('opacity') == 0; });
    
    var tile1 = $(vis[Math.floor(Math.random() * vis.length)]);
    var tile2 = $(invis[Math.floor(Math.random() * invis.length)]);

    $(tile1).fadeTo('fast', 0);
    $(tile2).fadeTo('fast', 0.55);
    
}

google.setOnLoadCallback(function () {
    $(".map-holder").hide().slideDown(500);
    $(".map-bottom-shadow").fadeIn(500);
    $("#map").hide().fadeIn(500);
    init();
});


$(function () {
    $(".main-info div").hide();
    $(".controls .road").click(function () {
        map.setMapTypeId(google.maps.MapTypeId.ROADMAP);
        $(".controls .satellite").removeClass("satelliteon").addClass("blue");
        $(".controls .road").addClass("roadon").addClass("blue");
        $(".grid").addClass("gridblue");
        for (var i = 0; i < tiles.length; i++) {
            var tile = tiles[i];
            if (tile.type == "rect") {
                tile.el.attr({ "fill": "90-#192f52-#537bbb" }); $(tile.el.node).css('opacity', .45);
            }
        }
    });
    $(".controls .satellite").click(function () {
        map.setMapTypeId(google.maps.MapTypeId.SATELLITE);
        $(".controls .satellite").addClass("satelliteon").removeClass("blue");
        $(".controls .road").removeClass("roadon").removeClass("blue");
        $(".grid").removeClass("gridblue");
        for (var i = 0; i < tiles.length; i++) {
            var tile = tiles[i];
            if (tile.type == "rect") {
                tile.el.attr({ "fill": "90-#c0c0c0-#FFFFFF" }); $(tile.el.node).css('opacity', .55);
            }
        }
    });
    var tilearray = [[0, 1, 2, 3, 4, 5, 6, 7], [2, 4, 6, 7], [3, 5, 7], [0, 1, 2, 3, 4, 5, 6, 7]];

    var R = Raphael("tiles", 1125, 561);

    var ieOld = $(".lt-ie9").length > 0;

    for (var i = 0; i < tilearray.length; i++) {
        for (var j = 0; j < tilearray[i].length; j++) {
            var tile = R.rect(5 + (141 * tilearray[i][j]), 5 + (140 * i), 132, 132, 3).attr({ "fill": "90-#c0c0c0-#FFFFFF", "stroke": "none" });
            if (ieOld) {
                $(tile.node).css('opacity', 0.55);
            } else {
                $(tile.node).css('opacity', 0);
            }
            tiles.push({ "type": "rect", "el": tile });
        }
    }
    var infoTile = R.rect(5, 145, 273, 273, 6).attr({ fill: "90-#c0c0c0-#FFFFFF", "fill-opacity": .9, stroke: "none" });

    function addTile(x, y, imgSrc, sector) {
        var tile1 = R.set();
        tile1.front = R.image(imgSrc, x, y, 132, 132).transform("s1,1");
        tile1.back = R.image(imgSrc.replace(".png", "flip.png"), x, y, 132, 132).transform("s-1,1r-5").attr({ "opacity": 0 });
        tile1.rect = R.rect(x, y, 132, 132, 3)
                        .attr({ fill: "#FFFFFF", "fill-opacity": 0, stroke: "none", "cursor": "pointer" })
                        .mouseover(function () {
                            showTile(tile1);
                        })
                        .mouseout(function () {
                            hideTide(tile1);
                        })
                        .click(function () {
                            loadVertical(tile1); 
                        });
        tile1.sector = sector;
        tile1.push(
            tile1.front,
            tile1.back,
            tile1.rect
            );
        tiles.push({ "type": "set", "el": tile1 });
    }
    addTile(428, 145, "img/tiles/telco.png", "telco");
    addTile(710, 145, "img/tiles/utilities.png", "utilities");
    addTile(287, 285, "img/tiles/resource.png", "resource");
    addTile(569, 285, "img/tiles/government.png", "government");
    addTile(851, 285, "img/tiles/financial.png", "financial");


    var E = Raphael("earth", 1146, 612);
    var earth = E.image("img/earth.jpg", -133.5, -116.5, 1413, 845);
    earth.transform("s10,10r15").attr({ "opacity": 0 }).hide();

    function showTile(tile) {
        $(".main-info div:visible").stop().fadeOut(500, function () { $(".main-info div." + tile.sector).stop().hide().css({ opacity: 1 }).fadeIn(500); });
        tile.back.stop().animate(Raphael.animation({ "opacity": 1 }, 0).delay(500)).animate({ transform: "s1,1r0" }, 1000, "<>");
        tile.front.stop().animate(Raphael.animation({ "opacity": 0 }, 0).delay(500)).animate({ transform: "s-1,1r5" }, 1000, "<>");
    }
    function hideTide(tile) {
        tile.back.stop().animate(Raphael.animation({ "opacity": 0 }, 0).delay(500)).animate({ transform: "s-1,1r-5" }, 1000, "<>");
        tile.front.stop().animate(Raphael.animation({ "opacity": 1 }, 0).delay(500)).animate({ transform: "s1,1" }, 1000, "<>");
        $(".main-info div:visible").stop().fadeOut(500, function () { $(".main-info div.default").stop().hide().css({ opacity: 1 }).fadeIn(500); });
    }
    function loadVertical(tile) {
        var ieOld = $(".lt-ie9").length > 0;
        for (var i = 0; i < tiles.length; i++) {
            if (ieOld) {
                ieOldFadeOut(tiles[i], Math.floor(Math.random() * 1000), Math.floor(Math.random() * 1500), tile);
            } else {
                fadeOut(tiles[i], Math.floor(Math.random() * 1000), Math.floor(Math.random() * 1500), tile);
            }
        }
        $(".grid").fadeOut(500);
        if (ieOld) {

            $(".main-info, .controls").fadeOut(1500);
            infoTile.stop().animate(Raphael.animation({ transform: "s0,1r0" }, 2000, "<>", function () {
                infoTile.remove();
            }));

            if (tile.front.attr("opacity") <= 0) {
                tile.rect.remove();
                tile.front.remove();
                tile.back.stop().animate(Raphael.animation({ transform: "s0,1r0" }, 500, "<>", function () {
                    tile.back.remove();
                }));
            } else {
                tile.back.remove();
                tile.rect.remove();
                tile.front.stop().animate(Raphael.animation({ transform: "s0,1r0" }, 500, "<>", function () {
                    tile.front.remove();
                }));
            }
        } else {

            $(".controls").fadeOut(1500);
            $(".main-info").fadeOut(500, function () {
                infoTile.stop().animate(Raphael.animation({ transform: "s-1,1r0" }, 1000, "<>"));
            });
            $(infoTile.node).animate({
                "opacity": 0
            }, 1500, function () {
                infoTile.remove();
            });
            $(tile.back.node).animate({
                opacity: 0
            }, 500, function () {
                tile.back.remove();
                tile.front.remove();
                tile.rect.remove();
            });
        }
        clearInterval(motionInterval);
        if (ieOld) {
            $("#earth").show();
            earth.show().transform("s1,1").animate(Raphael.animation({ "opacity": 1 }, 1000, ">").delay(2000));
        } else {
            earth.show().animate({ transform: "s1,1", "opacity": 1 }, 2500, ">");
        }
        setTimeout(function () { $(".earthshim").show(); loadDemo(tile.sector); }, 3000);
    }

    function mapZoom(zoom) {
        if (zoom > 3) {
            setTimeout(function () {
                mapZoom(zoom - 1);
            }, 500);
            map.setZoom(zoom - 1);
        }
        if (zoom == 3) {
            map.panTo(new google.maps.LatLng(-34.397, 150.644));
        }
    }
    function ieOldFadeOut(tile, delay, fadeDelay, selected) {
        if (tile.type == "rect") {
            tile.el.stop().animate(Raphael.animation({ transform: "s0,1r0", opacity: 0 }, 1500, "<>", function () {
                tile.el.remove();
            }).delay(delay));
        } else {
            if (tile.el.sector != selected.sector) {
                tile.el.rect.remove();
                tile.el.back.remove();
                setTimeout(function () {
                    tile.el.front.stop().animate(Raphael.animation({ "opacity": 0 }, 0).delay(750)).animate({ transform: "s0,1r2.5" }, 1500, "<>", function () {
                        tile.el.front.remove();
                    });
                }, delay);
            }
        }
    }
    function fadeOut(tile, delay, fadeDelay, selected) {
        if (tile.type == "rect") {
            tile.el.stop().animate(Raphael.animation({ transform: "s-1,1r0" }, 1500, "<>").delay(delay));
            setTimeout(function () {
                $(tile.el.node).animate({
                    opacity: 0
                }, 500, function () {
                    tile.el.remove();
                });
            }, fadeDelay);
        } else {
            if (tile.el.sector != selected.sector) {
                tile.el.rect.remove();
                tile.el.back.remove();
                setTimeout(function () {
                    tile.el.front.stop().animate(Raphael.animation({ "opacity": 0 }, 0).delay(750)).animate({ transform: "s0,1r2.5" }, 1500, "<>");
                }, delay);
                setTimeout(function () {
                    $(tile.el.front.node).animate({
                        opacity: 0
                    }, 500, function () {
                        tile.el.front.remove();
                    });
                }, fadeDelay);
            }
        }
    }
    R.renderfix();
});
(function ($) {
    $.fn.vAlign = function () {
        return this.each(function (i) {
            var h = $(this).height();
            var oh = $(this).outerHeight();
            var mt = (h + (oh - h)) / 2;
            $(this).css("margin-top", "-" + mt + "px");
            $(this).css("top", "50%");
            $(this).css("position", "absolute");
        });
    };
})(jQuery);
